<template>
  <section class="editor-container">
    <vue-neditor-wrap
      ref="neditor"
      v-model:modelValue="content"
      :init="init"
      :config="getConfigs"
      :destroy="false"
      @errorListslice="contentArrslice"
      @ready="ready"
      @input="setContent"
    ></vue-neditor-wrap>
    <a-upload
      class="word-uploader"
      :before-upload="beforeUpload"
      :custom-request="(file) => handleUpload(file)"
    >
      <a-button style="display: none">
        <upload-outlined></upload-outlined>
        Click to Upload
      </a-button>
    </a-upload>
    <uploadDialong
      @uploadFinished="handleConfirm"
      @handleCancle="handleCancle"
      :isVisible="isVisible"
      :uploadType="uploadType"
    ></uploadDialong>
  </section>
</template>
<script>
import { defineExpose } from "vue";
import VueNeditorWrap from "@/components/plugin/Print/neditor.vue";
// eslint-disable-next-line camelcase
import ueditor_markPlus from "@/utils/UeditorMark";
import ueditortable from "./ueditortable.ts";
import uploadDialong from "@/components/uploadDialog/uploadDialong.vue";
import request from "@/api/index";

export default {
  mixins: [ueditortable],
  directives: {
    drag: {
      // 指令的定义
      bind: function (el) {
        let oDiv = el; // 获取当前元素
        oDiv.onmousedown = (e) => {
          // 算出鼠标相对元素的位置
          let disX = e.clientX - oDiv.offsetLeft;
          let disY = e.clientY - oDiv.offsetTop;
          document.onmousemove = (e) => {
            // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            let left = e.clientX - disX;
            let top = e.clientY - disY;
            // if (top > 50 && top < 490) {
            oDiv.style.top = top + "px";
            // }
            // if (left > 11 && left < 493) {
            oDiv.style.left = left + "px";
            // }
          };

          document.onmouseup = (e) => {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      },
    },
  },
  name: "UEditor",
  components: {
    VueNeditorWrap,
    uploadDialong,
  },
  props: ["modelValue", "isWechatUpload", "options", "blurEditor"],
  watch: {
    modelValue: {
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.content = newVal;
        }
        //this.ueditortable(val);
      },
      deep: true,
      immediate: true,
    },
  },

  data() {
    const handler = (editor, name) => {
      try {
        this.isVisible = true;
        this.uploadType = name;
        // editor.parent.$refs[name][0].showDialog();
      } catch (error) {}
    };
    return {
      isVisible: false,
      uploadType: "",
      // errorApi 接口异常或者网络异常时的显示
      errorApi: false,
      firstUseShow: false,
      isShowDrag: false, // 可拖动窗口
      slicesystem: true,
      loading: true,
      oldval: [], // 用于记录content钟的值
      newval: [], // 新的值
      innnerText: "", // iframe的文字
      contentTxt: "", // 纯文本
      information: {}, // 获取用户信息
      dialogVisible: false, // 控制弹窗显示
      contentArr: [], // 从后台获取的内容数组
      resultCode: 1, // 后台返回的code码
      resultIndex: 0, // 第几次修改
      config: {
        // 如果需要上传功能,找后端小伙伴要服务器接口地址
        serverUrl: "",
        // 您的UEditor资源存放的路径,相对于打包后的index.html
        // UEDITOR_HOME_URL: '/NEditor/',
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 140,
        // 初始容器宽度
        initialFrameWidth: "50%",
        // 是否启用元素路径
        elementPathEnabled: false,
        // 是否开启字数统计
        wordCount: false,
        // 关闭自动保存
        enableAutoSave: false,
        // 打开右键菜单功能
        enableContextMenu: true,
        // 打开图片编辑功能
        // imagePopup: true,
        // 定义工具条
        toolbars: [
          [
            "source", // 源代码
            "undo", // 撤销
            "redo", // 重做
            "|",
            "insertcode", // 代码语言
            "fontfamily", // 字体
            "fontsize", // 字号
            "bold", // 加粗
            "italic", // 斜体
            "underline", // 下划线
            "forecolor", // 字体颜色
            "backcolor", // 背景色
            "removeformat", // 清除格式
            "autotypeset", // 自动排版
            "indent", // 首行缩进
            "pasteplain", // 纯文本粘贴模式
            "formatmatch", // 格式刷
            "|",
            "justifyleft", // 居左对齐
            "justifyright", // 居右对齐
            "justifycenter", // 居中对齐
            "justifyjustify", // 两端对齐
            "insertorderedlist", // 有序列表
            "insertunorderedlist", // 无序列表
            "rowspacingtop", // 段前距
            "rowspacingbottom", // 段后距
            "lineheight", // 行间距
            "link", // 超链接
            "unlink", // 取消链接
            "simpleupload", // 单图上传
            "insertimage", // 多图上传
            "insertvideo", // 视频
            "music", // 音乐
            "attachment", // 附件上传
            "wordimage", // 图片转存ß
            "pagebreak", // 分页
            "inserttable", // 插入表格
            "searchreplace", // 查询替换
            "|",
            "fullscreen", // 全屏
            "errorcorrection", // 纠错
            // 'imagecenter'// 居中
            // 'anchor', // 锚点
            // 'snapscreen', // 截图
            // 'strikethrough', // 删除线
            // 'subscript', // 下标
            // 'fontborder', // 字符边框
            // 'superscript', // 上标
            // 'blockquote', // 引用
            // 'selectall', // 全选
            // 'print', // 打印
            // 'preview', // 预览
            // 'horizontal', // 分隔线
            // 'time', // 时间
            // 'date', // 日期
            // 'insertrow', // 前插入行
            // 'insertcol', // 前插入列
            // 'mergeright', // 右合并单元格
            // 'mergedown', // 下合并单元格
            // 'deleterow', // 删除行
            // 'deletecol', // 删除列
            // 'splittorows', // 拆分成行
            // 'splittocols', // 拆分成列
            // 'splittocells', // 完全拆分单元格
            // 'deletecaption', // 删除表格标题
            // 'inserttitle', // 插入标题
            // 'mergecells', // 合并多个单元格
            // 'deletetable', // 删除表格
            // 'cleardoc', // 清空文档
            // 'insertparagraphbeforetable', // "表格前插入行"
            // 'paragraph', // 段落格式
            // 'edittable', // 表格属性
            // 'edittd', // 单元格属性
            // 'emotion', // 表情
            // 'spechars', // 特殊字符
            // 'map', // Baidu地图
            // 'gmap', // Google地图
            // 'help', // 帮助
            // 'directionalityltr', // 从左向右输入
            // 'directionalityrtl', // 从右向左输入
            // 'insertframe', // 插入Iframe
            // 'imagenone', // 默认
            // 'imageleft', // 左浮动
            // 'imageright', // 右浮动
            // 'attachment', // 附件
            // 'edittip ', // 编辑提示
            // 'customstyle', // 自定义标题
            // 'webapp', // 百度应用
            // 'touppercase', // 字母大写
            // 'tolowercase', // 字母小写
            // 'background', // 背景
            // 'template', // 模板
            // 'scrawl', // 涂鸦
            // 'drafts', // 从草稿箱加载
            // 'charts' // 图表
          ],
        ],
        REFUEDIT: this.$refs.neditor,
      },
      ue: null,
      buttons: [
        {
          name: "simpleupload",
          tip: "上传图片",
          handler,
        },
        {
          name: "insertimage",
          tip: "上传多图",
          handler,
        },
        {
          name: "insertvideo",
          tip: "上传视频",
          handler,
        },
        {
          name: "music",
          tip: "上传音频",
          handler,
        },
        {
          name: "attachment",
          tip: "上传文件",
          handler,
        },
        {
          name: "errorcorrection",
          tip: "纠错",
          handler,
        },
      ],
      wordBtn: {
        name: "wordimage",
        tip: "文件导入",
        handler(editor, name) {
          // 需要判断是第几个点的
          if (
            document.querySelector("#cardEdit") &&
            document
              .querySelector("#cardEdit")
              .querySelectorAll(".el-tabs__item")
          ) {
            let button = document
              .querySelector("#cardEdit")
              .querySelectorAll(".el-tabs__item");
            var isact = 0;
            for (let i = 0; i < button.length; i++) {
              if (button[i].className.indexOf("is-active") > -1) {
                isact = i;
              }
            }
            document.querySelectorAll(".word-uploader input")[isact].click();
          } else {
            document.querySelectorAll(".word-uploader input")[0].click();
          }
        },
      },
      errorCorrectionBtn: {
        //
        name: "errorcorrection",
        // icon: '@/icon/svg/bianji.svg',
        tip: "纠错",
        handler: (editor, name) => {
          this.textErrorCorrection();
        },
      },
      importCombox: {
        name: "wordimage",
        tip: "导入Word",
        handler(editor, cmdName, value) {
          document.querySelector(".avatar-uploader input").click();
        },
        items: [
          {
            label: "带格式",
            value: 1,
            renderLabelHtml: function () {
              return (
                '<div class="edui-label %%-label" style="line-height:2;font-size: 14px;">' +
                (this.label || "") +
                "</div>"
              );
            },
          },
          {
            label: "纯文本",
            value: 2,
            renderLabelHtml: function () {
              return (
                '<div class="edui-label %%-label" style="line-height:2;font-size: 14px;">' +
                (this.label || "") +
                "</div>"
              );
            },
          },
        ],
      },
    };
  },

  computed: {
    contentArrLength() {
      let i = 0;
      this.contentArr.forEach((item) => {
        if (item.cur) {
          i++;
        }
      });

      return i;
    },
    getConfigs() {
      this.config.initialFrameWidth = this.options.initialFrameWidth;
      return {
        ...this.config,
        ...(this.options || {}),
      };
    },
  },
  created() {
    // this.ifFirstUse();
  },
  methods: {
    setContent(val) {
      this.$emit("update:modelValue", val);
    },
    handleCancle() {
      this.isVisible = false;
    },
    // 用户改动文本时 触发的逻辑
    contentArrslice() {
      // let dom = document
      //   .querySelector('iframe')
      //   .contentDocument.querySelector('body')
      //   .getElementsByClassName('higspan')
      // let olddom = []
      // for (let i = 0; i < dom.length; i++) {
      //   olddom.push(dom[i].attributes['data-index'].nodeValue)
      // }
      // this.oldval = this.newval
      // this.newval = olddom
      // if (this.oldval.length > this.newval.length) {
      //   this.oldval.forEach((item, index) => {
      //     // eslint-disable-next-line eqeqeq
      //     if (this.newval.indexOf(item) == -1) {
      //       this.contentArr.splice(item - 0, 1, {})
      //     }
      //   })
      // }
    },
    // 将数组按照下标来排序
    compare(property) {
      return (a, b) => {
        let value1 = a[property];
        let value2 = b[property];
        return value1 - value2;
      };
    },

    unique(arr1) {
      const res = new Map();
      return arr1.filter((item) => !res.has(item.pos) && res.set(item.pos, 1));
    },
    // 一键修改
    oneClickModify() {
      // 修改时关闭 监听
      this.slicesystem = false;
      // ueditor_markPlus.oneClickModify()
      let arr1 = JSON.parse(JSON.stringify(this.contentArr));
      arr1.forEach((item, index) => {
        // console.log(item)
        this.modify(0);
      });
      // 修改完成后 删除错误数组
      // this.contentArr = []
    },
    // 单个修改
    modify(index) {
      let num = this.contentArr[index].cur.length;
      let modiyIndex = 0;
      for (var i = 0; i < index; i++) {
        modiyIndex += this.contentArr[i].cur.length;
      }
      console.error(modiyIndex);
      // for (var k = 0; k < num; k++) {
      ueditor_markPlus.modify(modiyIndex, this.contentArr);
      // }
      // this.contentArr.splice(index, 1)
    },
    //  重新检测
    again() {
      this.slicesystem = true;
      this.resultIndex = 0;
      this.contentArr = [];
      this.loading = true;
      this.textErrorCorrection();
    },

    // 用户未登录 进行登录
    login() {
      let model = document.querySelector(".v-modal");
      model.click();
      // /service/index
      this.$router.push({
        path: "/service/index",
      });
    },
    // 用户余额不足
    purchase() {
      let model = document.querySelector(".v-modal");
      model.click();
      this.$router.push({
        name: "serviceIndex",
        // path: '/service/index',
        params: {
          url: "https://order.yun.jeecms.com/#/service/apply/index?type=%E6%99%BA%E8%83%BD%E7%BA%A0%E9%94%99&appCode=34974987165458&appId=111&userName=system",
        },
      });
    },
    // 获取用户信息
    getpickUpInformation() {
      this.$request.fetchpickUpInformation().then((res) => {
        this.information = res.data;
        // console.log('用户手机号', res.data)
      });
    },
    // 判断用户是否时数次使用
    ifFirstUse() {
      let params = { name: "textErrorCorrection" };
      this.$request.proofreading(params).then((res) => {
        this.firstUseShow = !res.data;
        // true 表示使用过 没使用过就是false
        if (!res.data) {
          // 调用接口
          this.$request.proofuser(params).then((res2) => {});
        }
      });
    },
    // 是首次点击我知道了
    idogit() {
      this.firstUseShow = false;
    },
    textErrorCorrection() {
      // 发送请求时设置不可编辑
      ueditor_markPlus.inspect(this);
      let contentTxt = this.$refs.neditor._getContentTxt().replace(/\t/g, "");

      if (contentTxt == "") {
        this.$message("请填写内容后进行校验");
      } else {
        this.isShowDrag = true;
        this.$request.fetchpickUpInformation().then((res) => {
          this.information = res.data;
          // console.log('用户手机号', res.data)

          // let contentHTML = this.$refs.neditor._getContentHtml()
          // this.dialogVisible = true
          // 智能纠错逻辑
          let data = {
            mobile: this.information.mobile,
            appId: this.information.productAppId,
            text: contentTxt,
          };
          // eslint-disable-next-line eqeqeq
          if (this.resultIndex == 0) {
            // eslint-disable-next-line eqeqeq
            if (this.content == "") {
            } else {
              this.$request
                .fetchTextCorrection(data)
                .then((res) => {
                  // 成功请求
                  this.errorApi = false;
                  // 请求已经完成，释放开进入可编辑
                  this.$refs.neditor._setEnabled();
                  // console.log(res.data)
                  // res.data.resultCode = 3
                  switch (res.data.resultCode) {
                    case 1:
                      this.resultCode = 1;
                      this.isShowDrag = false;
                      this.dialogVisible = true;
                      break;
                    case 2:
                      this.loading = false;
                      this.resultIndex += 1;
                      // this.contentArr = res.data.results
                      this.resultCode = 2;
                      this.contentArr = res.data.results;
                      // 获取到数组后 按照其 错误下标进行排序
                      this.contentArr = this.contentArr.sort(
                        this.compare("pos")
                      );
                      setTimeout(() => {
                        // eslint-disable-next-line eqeqeq
                        if (this.contentArr.length != 0) {
                          this.contentArr = this.unique(
                            JSON.parse(JSON.stringify(this.contentArr))
                          );
                          ueditor_markPlus.ueditor_markPlus(
                            this.contentArr,
                            this
                          );
                          // ueditor_mark.ueditor_mark(contentTxt, this.contentArr, this)
                        }
                      }, 50);

                      break;
                    case 3:
                      this.resultCode = 3;
                      this.isShowDrag = false;
                      this.dialogVisible = true;
                      break;
                  }
                })
                .catch((err) => {
                  // 此时为检测异常
                  console.log(err);
                  this.$refs.neditor._setEnabled();
                  this.loading = false;
                  this.errorApi = true;
                });
            }
          }
        });
      }
    },

    ready(editor) {
      this.ue = editor;
      this.$refs.neditor.readyValue = this.content || "";
    },
    handleConfirm(html) {
      this.isVisible = false;
      // html = `<img src='http://pic37.nipic.com/20140113/8800276_184927469000_2.png'  style='max-width:750px'/>`
      this.ue.execCommand("insertHtml", html);
    },
    beforeUpload(file) {
      // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
      return new Promise((resolve, reject) => {
        // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
        const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
        let isFileType = true;
        if (["doc", "docx", "xls", "pdf", "ppt", "ofd", "xlsx"].length) { 
          isFileType = ["doc", "docx", "xls", "pdf", "ppt", "ofd", "xlsx"].includes(backgFix);

          if (!isFileType) {
            this.$message.error(
              `只能上传${["doc", "docx", "xls", "pdf", "ppt", "ofd", "xlsx"].join(",")}格式文件!`
            );
            return false;
          }
        }

        if (isFileType) {
          // fileList.value = [...fileList.value, file];
          return resolve(true);
        }
      });
    },
    handleUpload(file) {
      console.log(file, "files");
      const param = new FormData();
      param.append("type", 1);
      param.append("file", file.file, file.file.name);
      request.fetchDocImport(param).then((res) => {
        if (res.code === "00000 00000") {
          this.$message.success(res.message);
          this.ue.execCommand("insertHtml", res.data);
        }
      });
    },
    init() {
      if (this.$refs.neditor) {
        this.buttons.forEach(this.$refs.neditor.registerButton);
        this.$refs.neditor.registerButton(this.wordBtn);
        this.$refs.neditor.registerButton(this.errorCorrectionBtn);
      }
    },
    REFS() {
      return this.$refs.neditor;
    },
  },
};
</script>
<style lang="scss">
.editor-container {
  padding: 0;

  .edui-notadd .edui-editor {
    z-index: 500 !important;
    border: 1px solid rgba(0, 0, 0, 0.15);

    > div:not([id]) {
      height: 0 !important;
    }

    &[style~="absolute;"] {
      width: 1200px !important;
      left: 50% !important;
      transform: translateX(-50%);
      padding: 0 3000px;
      box-sizing: content-box;
      background: #f0eff2;

      .edui-editor-iframeholder {
        background-color: #fff;
      }
    }
  }

  .edui-notadd .edui-editor-open {
    z-index: 99 !important;
  }

  .edui-editor-toolbarbox.edui-notadd {
    position: relative !important;
    z-index: 500;

    .edui-editor-toolbarboxouter {
      background-color: #ffffff;
      padding: 8px 15px 6px;

      .edui-state-hover {
        > .edui-notadd {
          background-color: #f3f3f3;
        }
      }

      .edui-state-checked,
      .edui-state-active {
        > .edui-notadd {
          background-color: #e5e5e5;
        }
      }

      .edui-icon,
      .edui-state-checked .edui-icon {
        color: #777777;
      }

      .edui-icon {
        font-size: 18px;
      }

      .edui-state-checked,
      .edui-state-hover {
        .edui-icon::before {
          display: none;
        }

        .edui-icon .edui-iconfont {
          display: block;
        }
      }
    }

    .edui-for-forecolor,
    .edui-for-backcolor,
    .edui-for-autotypeset,
    .edui-for-insertorderedlist,
    .edui-for-insertunorderedlist,
    .edui-for-rowspacingtop,
    .edui-for-rowspacingbottom,
    .edui-for-lineheight {
      .edui-box.edui-arrow.edui-notadd {
        margin-right: -4px;
      }
    }
  }

  .edui-notadd.edui-editor-bottomContainer {
    border: 0;
  }

  .word-uploader {
    height: 0px;
    overflow: hidden;

    .ant-upload-list {
      display: none;
    }
  }

  .resuBox {
    display: flex;
    justify-content: left;

    div {
      margin-right: 10px;

      span {
        color: red;
      }
    }
  }

  .resultTable {
    display: flex;
    justify-content: space-between;

    .correct {
      padding-left: 10px;
      text-align: left;
      flex: 1;
    }

    .modify {
      color: rgb(44, 161, 182);
    }
  }

  .elDialog {
    background-color: #666666;

    .center {
      width: 403px;
      margin: auto;
      display: flex;

      .el-icon-warning {
        margin-right: 10px;
      }

      .text {
        margin-top: 7px;
        line-height: 19px;
      }
    }

    .el-dialog {
      width: 500px !important;
      height: 208px;
      position: relative;

      .el-button {
        position: absolute;
        bottom: 30px;
        right: 30px;
        width: 101px;
        height: 31px;
        box-sizing: border-box;
        padding: 0;
      }
    }
  }

  .elDialog2 {
    background-color: transparent;
  }

  .firstUse {
    width: 308px;
    height: 163px;
    background-color: #4e83fd;
    position: absolute;
    top: 78px;
    left: 453px;
    border-radius: 10px;
    z-index: 10;

    .tips1 {
      border: 8px solid transparent;
      border-bottom: 8px solid #4e83fd;
      top: -16px;
      left: 178px;
      position: absolute;
      width: 0;
      height: 0;
    }

    .tipstitle {
      line-height: 1;
      color: white;
      font-size: 14px;
      margin: auto;
      width: 258px;
      text-align: left;
      margin-top: 24px;
      font-weight: 600;
    }

    .tipscenter {
      margin: auto;
      width: 258px;
      text-align: left;
      margin-top: 13px;
      line-height: 20px;
      color: white;
    }

    .button {
      border-radius: 2px;
      cursor: pointer;
      display: block;
      margin: auto;
      padding: 0;
      height: 30px;
      margin: auto;
      margin-top: 22px;
      background-color: white;
      font-size: 14px;
      text-align: center;
      width: 258px;
      border: none;
    }
  }

  .drag-box {
    border-radius: 4px;
    z-index: 999;
    position: fixed;
    top: 365px;
    left: 757px;
    width: 276px;
    background: #ffffff;
    border-radius: 5px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

    .drag-title {
      color: #333333;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      user-select: none;
      position: absolute;
      top: 0;
      white-space: nowrap;
      cursor: pointer;
      width: 276px;
      height: 65px;
      background-color: #fff;
      border-bottom: 1px solid #ededed;
      font-size: 18px;
      line-height: 65px;
      text-align: left;
      text-indent: 24px;

      .el-icon-close {
        float: right;
        color: #999999;
        font-size: 20px;
        margin-right: 18px;
        margin-top: 18px;
      }
    }

    .loading {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      width: 276px;
      height: 150px;
      position: absolute;
      top: 65px;
      background-color: white;
      z-index: 10;
      text-align: center;

      .el-icon-loading {
        margin-top: 30px;
        font-size: 44px;
      }
    }

    .notYet {
      background-color: white;
      position: absolute;
      top: 66px;
      width: 276px;
      height: 65px;
      box-sizing: border-box;
      line-height: 65px;
      padding-left: 26px;

      div {
        float: left;
        color: #666666;
      }

      .again {
        cursor: pointer;
        color: #1fd0e9;
        margin-left: 43px;
        margin-right: 15px;
        cursor: pointer;
      }

      .oneclick {
        color: #1ec6df;
        cursor: pointer;
      }
    }

    .errorContent {
      width: 276px;
      max-height: 290px;
      overflow-y: scroll;
      margin-top: 130px;

      .errorList {
        color: #333333;
        width: 228px;
        margin: auto;
        font-size: 12px;
        height: 12px;
        margin-top: 12px;
        margin-bottom: 12px;
        line-height: 1;

        .modifycur {
          float: left;
        }

        .arrow {
          float: left;
          margin-left: 10px;
          margin-right: 10px;
        }

        .modifycurry {
          float: left;
        }

        .modifyButton {
          color: #1fd0e9;
          float: right;
          cursor: pointer;
        }
      }
    }
  }

  iframe {
    .markspan {
      border-bottom: 1px solid #090;
    }
  }
}
</style>
<style scoped>
.button:hover {
  background-color: rgba(255, 255, 255, 0.9);
  color: #262626;
}
</style>
